<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
          />

      </el-form-item>
      <el-form-item label="文章来源" prop="articleOrigin">
        <el-input v-model="queryParams.articleOrigin" placeholder="请输入文章来源" clearable
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="栏目名称" prop="columnId">
        <el-select v-model="queryParams.columnId" placeholder="请选择栏目名称" clearable filterable>
          <el-option v-for="item in columnOptions" :key="item.columnId" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="责任编辑" prop="author">
        <el-input v-model="queryParams.author" placeholder="请输入责任编辑" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['toutiao:toutiao:add']"
        >新增</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['toutiao:toutiao:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['toutiao:toutiao:remove']">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['toutiao:toutiao:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="toutiaoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" />
      <el-table-column label="标题" align="center" prop="title" >
        <template slot-scope="scope">
          {{ $stripHtml(scope.row.title) }}
        </template>
      </el-table-column>
      <el-table-column label="文章来源" align="center" prop="articleOrigin" />
      <el-table-column label="栏目名称" align="center" prop="columnName" />
      <el-table-column label="内容" align="center" prop="content"  >
        <template slot-scope="scope">
          <div class="content-cell">{{ $formatContent(scope.row.content) }}</div>
        </template>
      </el-table-column>>
      <el-table-column label="责任编辑" align="center" prop="author" />
      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column label="封面路径" align="center" prop="coverPath">
        <template slot-scope="scope">
          <image-preview :src="scope.row.coverPath" width="50" height="50"/>
        </template>
</el-table-column> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['toutiao:toutiao:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['toutiao:toutiao:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改toutiao对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <!-- <el-input v-model="" type="textarea" placeholder="请输入内容" /> -->
          <enhanced-editor v-model="form.title" :min-height="120" :max-height="200" placeholder="请输入内容"/>
        </el-form-item>
        <!-- 副标题部分 -->
        <el-form-item label="副标题">
          <div v-for="(subtitle, index) in subtitles" :key="index" class="subtitle-item">
          <enhanced-editor v-model="form[`littleTitle${index + 1}`]" :placeholder="`请输入副标题${index + 1}`"  :min-height="120" :max-height="200" />

            <!-- <el-input v-model="form[`littleTitle${index + 1}`]" :placeholder="`请输入副标题${index + 1}`" /> -->
          </div>
          <el-button v-if="subtitles.length < 2" type="text" icon="el-icon-plus" @click="addSubtitle">
            添加副标题
          </el-button>
        </el-form-item>
        <el-form-item label="文章来源" prop="articleOrigin">
          <el-input v-model="form.articleOrigin" placeholder="请输入文章来源" />
        </el-form-item>
        <el-form-item label="栏目名称" prop="columnId">
          <el-select clearable filterable v-model="form.columnId" placeholder="请选择">
            <el-option placeholder="请选择" v-for="item in columnOptions" :key="item.id" :label="item.name"
              :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="责任编辑" prop="author">
          <el-input v-model="form.author" placeholder="请输入责任编辑" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <!-- <el-form-item label="封面路径" prop="coverPath">
          <input type="file" @change="handleFileChange" ref="fileInput">
          <div v-if="originalFilePath">当前文件路径：{{ originalFilePath }}</div>
          <div v-if="isFileSelected">
            已选文件：{{ form.coverPath.name }}
          </div>
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listToutiao, getToutiao, delToutiao, addToutiao, updateToutiao,
  addToutiaoOwn, updateToutiaoOwn
} from "@/api/toutiao/toutiao";
import { listConlumn, getConlumn, listConlumnList } from "@/api/conlumn/conlumn";
import EnhancedEditor from "@/components/Editor/EnhancedEditor";

export default {
  name: "Toutiao",
  components: {
    EnhancedEditor
  },
  data() {
    return {
      subtitles: [], // 用于存储副标题的动态数量
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // toutiao表格数据
      toutiaoList: [],
      columnOptions: [],
      originalFilePath: "",
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        articleOrigin: null,
        columnId: null,
        content: null,
        author: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        columnId: [
          { required: true, message: "栏目id不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "内容不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getColumnList();
    this.getList();
  },
  computed: {
    isFileSelected() {
      return this.form.coverPath instanceof File;
    }
  },
  methods: {

    addSubtitle() {
      if (this.subtitles.length < 2) {
        this.subtitles.push(`littleTitle${this.subtitles.length + 1}`);
      }
    },


    handleFileChange(event) {
      const file = event.target.files[0]; // 获取原生 File 对象
      this.form.coverPath = file;
      console.log(file);
    },
    formatContent(row, column, cellValue, index) {
      const maxLength = 20; // 可根据实际需求调整截取的长度
      if (cellValue && cellValue.length > maxLength) {
        return cellValue.substring(0, maxLength) + '...';
      }
      return cellValue;
    },
    /** 查询栏目列表 */
    getColumnList() {
      listConlumnList().then(response => {
        this.columnOptions = response.rows;
      });
    },

    /** 查询toutiao列表 */
    getList() {
      this.loading = true;
      listToutiao(this.queryParams).then(response => {
        console.log(this.columnOptions);
        //查找columnId对应的栏目名称
        this.toutiaoList = response.rows.map(item => {
          const column = this.columnOptions.find(col => col.id === item.columnId);
          return {
            ...item,
            columnName: column ? column.name : '未知栏目'
          }
        })
        this.total = response.total;
        this.loading = false;
      });
    },


    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        articleOrigin: null,
        columnId: null,
        content: null,
        author: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null,
        coverPath: null,
        littleTitle1: null, // 清空副标题1
        littleTitle2: null, // 清空副标题2
      };
      this.subtitles = []; // 清空副标题数组
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加头条";
      if (this.$refs.fileInput) {
        this.$refs.fileInput.value = '';
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getToutiao(id).then(response => {
        this.form = response.data;
        this.originalFilePath = this.form.coverPath || '';
        this.open = true;
        this.title = "修改头条";
        // 同步副标题状态 - 修改部分1：初始化时检查已有的副标题
        this.subtitles = [];
        // 检查是否存在副标题1，如果存在则添加到显示列表
        if (this.form.littleTitle1 || this.form.little_title1) {
          this.subtitles.push('littleTitle1');
        }
        // 检查是否存在副标题2，如果存在则添加到显示列表
        if (this.form.littleTitle2 || this.form.little_title2) {
          this.subtitles.push('littleTitle2');
        }
        // 如果没有任何副标题但允许添加，则默认显示一个空的副标题输入框
        if (this.subtitles.length === 0) {
          this.subtitles.push('littleTitle1');
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateToutiaoOwn(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addToutiaoOwn(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除toutiao编号为"' + ids + '"的数据项？').then(function () {
        return delToutiao(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('toutiao/toutiao/export', {
        ...this.queryParams
      }, `toutiao_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.subtitle-item {
  margin-bottom: 20px;
}
</style>
